Java编程题-使用数组模拟栈 发表于 2020-02-25 | 分类于 Java | 字数统计: 270 字 | 阅读时长 ≈ 1 分钟 栈:后进先出 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586// Stack类public class Stack { // 使用数组存储数据 Object[] elements; // 指向栈顶元素上方的一个帧 int index; // 栈默认的初始化容量是5 Stack() { this(2); } Stack(int max) { elements = new Object[max]; } // 压栈方法 public void push(Object element) throws StackOperationException { if (index == elements.length) { throw new StackOperationException("栈已满"); } elements[index++] = element; } // 弹栈方法 public Object pop() throws StackOperationException { if (index == 0) { throw new StackOperationException("栈已空!"); } return elements[--index]; }}// 异常类public class StackOperationException extends Exception { public StackOperationException() { } public StackOperationException(String msg) { super(msg); }}// 测试类public class StackTest { public static void main(String[] args) { Stack s = new Stack(); User u1 = new User("Jack", 20); User u2 = new User("Zhang", 21); User u3 = new User("Li", 22); // 压栈 try { s.push(u1); s.push(u2); s.push(u3); } catch (StackOperationException e) { e.printStackTrace(); } // 弹栈 try { System.out.println(s.pop()); System.out.println(s.pop()); // System.out.println(s.pop()); } catch (StackOperationException e) { e.printStackTrace(); } }}class User { String name; int age; User(String name, int age) { this.name = name; this.age = age; } public String toString() { return "User[name=" + name + ",age=" + age + "]"; }}